import React, { useEffect, useState } from "react";
import {
    Button,
    Col,
    Form,
    Input,
    message,
    Modal, Popconfirm,
    Row,
    Select,
    Space,
    Switch,
    Table,
    TableProps, Tag,
    Tooltip,
    Tree
} from 'antd';
import { DeleteOutlined, FormOutlined, PlusOutlined, QuestionCircleOutlined } from "@ant-design/icons";
import { handleTree, setKey, setKeyUtils } from "@/utils/Z.ts";


import useResponsiveLayout from "@/utils/useResponsiveLayout";
import { delExpression, listExpression } from "@/api/flowable/definition/expression";
import EditorExpressionView from "./component/EditorExpressionView";
import { globalMessage } from "@/utils/message";

const ExpressionView: React.FC = () => {
    const initialQueryParams = {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
    };

    interface DataType {
    }

    const [form] = Form.useForm();
    const [id, setId] = useState<string>(undefined);
    const [dataList, setDataList] = useState<DataType[]>([]);

    const columns: TableProps<DataType>['columns'] = [
        {
            title: '主键',
            dataIndex: 'id',
            key: 'id',
            align: 'center'
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            align: 'center'
        }, {
            title: '表达式内容',
            dataIndex: 'expression',
            key: 'expression',
            align: 'center'
        }, {
            title: '指定类型',
            dataIndex: 'dataType',
            key: 'dataType',
            align: 'center'
        },
        // {
        //     title: '状态',
        //     dataIndex: 'status',
        //     key: 'status',
        //     align: 'center',
        //     render: (_, record:any) => (
        //         <div><Tag color="processing">{record.status === "0" ? "正常" : "停用"}</Tag></div>
        //     )
        // },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (_, record: any) => (
                <Space size="middle">
                    <Button type="link" size="small" icon={<FormOutlined />}
                        onClick={() => EditClick(record)}>修改</Button>
                    <Button onClick={() => handleDelete(record)} type="link" size="small" icon={<DeleteOutlined />}
                    >删除</Button>
                </Space>
            ),
        },
    ];

    const [queryParams, setQueryParams] = useState(initialQueryParams);
    const [total, setTotal] = useState(0);
    const [key, setKey] = useState(0);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [title, setTitle] = useState('');
    const [open, setOpen] = useState<boolean>(false);
    useEffect(() => {
        getList();
    }, [queryParams]);  // 监听 queryParams 变化，调用 getList

    /** 查询用户列表 */
    function getList() {
        listExpression(queryParams).then((res: any) => {
            setDataList(setKeyUtils(res?.rows, { key: 'id' }))
            setTotal(res.total); // 更新 total，用于分页
        });
    }

    // 查询列表
    function handleSearch() {
        form.validateFields().then(values => {
            setQueryParams(prevQueryParams => ({
                ...prevQueryParams,
                name: values.name,
            }));
        });
    }

    // 重置查询
    const resetSearch = () => {
        form.resetFields();
        setQueryParams(initialQueryParams); // 重置为初始状态
    }
    // 分页变化
    const handleTableChange = (page: number, pageSize: number) => {
        setQueryParams({
            ...queryParams,
            pageNum: page,
            pageSize: pageSize,
        });
    };
    const handleAddClick = (e?: Record<string, any>) => {
        setKey(prev => prev + 1); // 每次打开时改变 key 值
        setId(undefined)
        setTitle("新增表达式")
        setOpen(true)
    }

    // 修改按钮
    const EditClick = (e: Record<string, any>) => {
        setKey(prev => prev + 1); // 每次打开时改变 key 值
        setId(e.id)
        setTitle("修改表达式")
        setOpen(true)
    }
    // 删除按钮
    const handleDelete = (e: Record<string, any>) => {
        const ids = e?.id || selectedRowKeys;
        Modal.confirm({
            title: '系统提示',
            content: (`是否确认删除编号为"${ids}"的数据项？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                delExpression(ids).then((res: any) => {
                    if (res?.code === 200) {
                         globalMessage().info("删除成功").then(r => {
                        })
                        getList()
                    }
                })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作

            },
        });
    }
    // 复选框选择参数赋值
    const onSelectChange = (newSelectedRowKeys) => {
        setSelectedRowKeys(newSelectedRowKeys);
    };
    // 复选框函数
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    return (
        <div className='home'>
            <Row gutter={20} style={{ paddingTop: "20px" }}>
                <Col span={24}>
                    <div>
                        <Form
                            form={form}
                            name="customized_form_controls"
                            style={{ marginTop: 10, marginLeft: 10, marginBottom: 10 }}
                            layout={useResponsiveLayout("inline")}>
                            <Form.Item
                                name="name"
                                label="名称">
                                <Input />
                            </Form.Item>
                            <Form.Item>
                                <Button type="primary" htmlType="submit" onClick={handleSearch} style={{
                                    marginRight: 20,
                                }}>
                                    查询
                                </Button>
                                <Button type="primary" htmlType="reset" onClick={resetSearch}>
                                    重置
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>
                    <div><Button type="primary" ghost onClick={() => {
                        handleAddClick()
                    }} style={{ margin: 10 }}>
                        新增
                    </Button>
                        <Button type="primary" ghost onClick={handleDelete} style={{ margin: 10 }}
                            disabled={selectedRowKeys.length === 0}>
                            批量删除
                        </Button>
                    </div>
                    <Table scroll={{ x: true }} rowSelection={rowSelection} columns={columns} dataSource={dataList} pagination={{
                        current: queryParams.pageNum,
                        pageSize: queryParams.pageSize,
                        total: total,
                        showSizeChanger: true, // 显示分页尺寸切换器
                        pageSizeOptions: ['10', '20', '50'], // 分页尺寸选项
                        onChange: handleTableChange
                    }} />
                </Col>
            </Row>
            {open && <EditorExpressionView key={key} title={title} open={open} id={id} OnCanCle={() => {
                setOpen(false);
                getList();
            }} />}


        </div>
    )
};
export default ExpressionView;
